import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/store_categories.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/product/product_category_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../theme.dart';

class HomeCategoryScreenArgs {
  final bool selectable;

  HomeCategoryScreenArgs(this.selectable);
}

/// 分类
class HomeCategoryScreen extends StatefulWidget {
  static const routeName = "/HomeCategoryScreen";
  final HomeCategoryScreenArgs args;

  const HomeCategoryScreen({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  _HomeCategoryScreenState createState() => _HomeCategoryScreenState();
}

class _HomeCategoryScreenState extends State<HomeCategoryScreen> {
  String _error;
  List<Category> _listParent;
  int _currentParentId;
  List<Category> _list;

  @override
  void initState() {
    super.initState();
    _fetchCategoryParent();
  }

  @override
  Widget build(BuildContext context) {
    return _error == null && _listParent == null
        ? Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          )
        : _listParent == null
            ? Scaffold(
                body: Center(
                  child: Text("$_error"),
                ),
              )
            : Scaffold(
                appBar: _buildAppBar(),
                body: _buildBody(),
              );
  }

  Widget _buildAppBar() {
    return AppBar(
      title: Text("商品分类"),
    );
  }

  Widget _buildBody() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 100.w,
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(vertical: 8.w),
            child: Wrap(
              runSpacing: 15.w,
              children: List.generate(
                _listParent.length,
                (index) => _buildParentItem(_listParent[index]),
              ),
            ),
          ),
        ),
        Expanded(
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(vertical: 8.w),
            child: Wrap(
              runSpacing: 8.w,
              children: List.generate(
                _list?.length ?? 0,
                (index) => _buildItem(_list[index]),
              ),
            ),
          ),
        )
      ],
    );
  }

  /// 一层
  Widget _buildParentItem(Category category) {
    return GestureDetector(
      onTap: () => _onTapParentItem(category),
      child: SizedBox(
        width: 100.w,
        child: Text(
          "${category.name}",
          style: TextStyle(
            color: _currentParentId == category.id ? Theme.of(context).primaryColor : kTextColor,
            fontSize: 16.sp,
          ),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  /// 点击父类
  void _onTapParentItem(Category category) {
    // 这里需要看是否可选择
    if (widget.args.selectable && !category.hasChildren) {
      Navigator.of(context).pop(category);
    } else {
      setState(() {
        _currentParentId = category.id;
      });
      _fetchCategory(_currentParentId);
    }
  }

  /// 二层
  Widget _buildItem(Category category) {
    return GestureDetector(
      onTap: () => _onTapItemOrChildItem(category),
      child: Container(
        padding: EdgeInsets.all(8.w),
        width: (375.0 - 100 - 8).w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.w),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("${category.name}", style: TextStyle(fontSize: 16.sp)),
            SizedBox(height: 8.w),
            Wrap(
              spacing: 8.w,
              runSpacing: 8.w,
              children: List.generate(
                category.children.length,
                (index) => _buildChildItem(category.children[index]),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 三层
  Widget _buildChildItem(Category category) {
    return GestureDetector(
      onTap: () => _onTapItemOrChildItem(category),
      child: Column(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4.w),
            child: ImageNetwork(url: "${category.imageUrl}", width: 75.w, height: 75.w),
          ),
          SizedBox(height: 5.w),
          Text("${category.name}"),
        ],
      ),
    );
  }

  /// 点击二、三层类型
  void _onTapItemOrChildItem(Category category) {
    // 这里需要看是否可选择
    if (widget.args.selectable) {
      Navigator.of(context).pop(category);
    } else {
      Navigator.of(context).pushNamed(
        ProductCategoryScreen.routeName,
        arguments: ProductCategoryScreenArgs("${category.name}", categoryId: category.id),
      );
    }
  }

  /// 父分类
  void _fetchCategoryParent() async {
    final api = context.read<Api>();
    try {
      final listParent = await api.category(1, null);
      if (!mounted) {
        return;
      }
      setState(() {
        _listParent = listParent.childCategoriesV2;
        _currentParentId = _listParent
            .firstWhere(
              (element) => element.hasChildren,
              orElse: () => null,
            )
            ?.id;
      });
      // 如果有父类，就立即查询下一层数据
      if (_currentParentId != null) {
        _fetchCategory(_currentParentId, showLoading: false);
      }
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
    } catch (e) {
      debugPrint("$e");
    }
  }

  /// 分类
  void _fetchCategory(int parentId, {bool showLoading = true}) async {
    final api = context.read<Api>();
    if (showLoading) {
      EasyLoading.show();
    }
    try {
      final list = await api.category(2, parentId);
      if (!mounted) {
        return;
      }
      if (showLoading) {
        EasyLoading.dismiss();
      }
      setState(() {
        _list = list.childCategoriesV2;
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      if (showLoading) {
        EasyLoading.showToast("${e.message}");
      }
    } catch (e) {
      debugPrint("$e");
    }
  }
}
